


const hostList = document.getElementById('hostList');
const hostDetails = document.getElementById('hostDetails');
let diskChart = null;
let cpuChart = null;
let memoryChart = null;

const pageSize = 12;
let currentPage = 1;

function renderPagination() {
  const totalPages = Math.ceil(hosts.length / pageSize);
  const pagination = document.getElementById("pagination");
  pagination.innerHTML = "";

  // 上一页按钮
  if (currentPage > 1) {
    const prevBtn = document.createElement("button");
    prevBtn.className = "btn btn-xs";
    prevBtn.textContent = "上一页";
    prevBtn.onclick = () => {
      currentPage--;
      renderHostList();
    };
    pagination.appendChild(prevBtn);
  }

  // 下一页按钮
  if (currentPage < totalPages) {
    const nextBtn = document.createElement("button");
    nextBtn.className = "btn btn-xs";
    nextBtn.textContent = "下一页";
    nextBtn.onclick = () => {
      currentPage++;
      renderHostList();
    };
    pagination.appendChild(nextBtn);
  }
}




function renderHostList() {

  const start = (currentPage - 1) * pageSize;
  const end = start + pageSize;
  const currentHosts = hosts.slice(start, end);
  
  hostList.innerHTML = ''; // 清空
  currentHosts.forEach((host, index) => {
    const li = document.createElement('li');

    const statusColor = host.online ? 'bg-green-500' : 'bg-gray-400';
    const disabled = host.online ? '' : 'disabled';
    const btnClass = host.online ? 'btn-outline btn-primary' : 'btn-disabled';

    li.innerHTML = `
<button class="btn w-full host-button ${btnClass}" ${disabled} onclick="showDetails(${index})">
<span class="flex items-center space-x-2">
  <span class="w-2 h-2 rounded-full ${statusColor}"></span>
  <span>${host.ip}</span>
</span>
</button>
`;
    hostList.appendChild(li);
  });

  renderPagination();
}


function showDetails(index) {
  const host = hosts[index];
  hostDetails.innerHTML = `
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div class="card glass-card shadow-md mt-4">
  <div class="card-body">
    <h2 class="card-title">系统负载</h2>
    <div class="grid grid-cols-3 gap-4 text-center">
      <div>
        <div class="text-sm text-gray-500">1 分钟</div>
        <div class="text-xl font-bold text-blue-700">${host.load[0]}</div>
      </div>
      <div>
        <div class="text-sm text-gray-500">5 分钟</div>
        <div class="text-xl font-bold text-yellow-600">${host.load[1]}</div>
      </div>
      <div>
        <div class="text-sm text-gray-500">15 分钟</div>
        <div class="text-xl font-bold text-red-600">${host.load[2]}</div>
      </div>
    </div>
    <!-- Chart canvas -->
    <div class="mt-4">
      <canvas id="loadChart" height="80"></canvas>
    </div>
  </div>
</div>

<div class="card bg-white shadow-lg rounded-xl glass-card p-6">
  <!-- Tabs -->
  <div role="tablist" class="tabs tabs-lg tabs-boxed mb-4">
    <a role="tab" class="tab tab-active " id="baseTab" onclick="switchInfoTab('base')">基础信息</a>
    <a role="tab" class="tab" id="hardwareTab" onclick="switchInfoTab('hardware')">硬件信息</a>
  </div>

  <!-- Tab 内容 -->
  <div id="baseInfo" class="space-y-2">

  <div class="grid grid-cols-1 md:grid-cols-1 gap-x-8 gap-y-3 text-sm">
  <div class="flex justify-between border-b border-base-200 pb-1">
    <span class="text-gray-500">主机名</span>
    <span class="font-medium text-base-content">${host.name}</span>
  </div>
  <div class="flex justify-between border-b border-base-200 pb-1">
    <span class="text-gray-500">IP 地址</span>
    <span class="font-medium text-base-content">${host.ip}</span>
  </div>
  <div class="flex justify-between border-b border-base-200 pb-1">
    <span class="text-gray-500">服务器型号</span>
    <span class="font-medium text-base-content">${host.model}</span>
  </div>
  <div class="flex justify-between border-b border-base-200 pb-1">
    <span class="text-gray-500">服务器 SN</span>
    <span class="font-medium text-base-content">${host.sn}</span>
  </div>
  <div class="flex justify-between border-b border-base-200 pb-1">
    <span class="text-gray-500">操作系统</span>
    <span class="font-medium text-base-content">${host.os}</span>
  </div>
  <div class="flex justify-between border-b border-base-200 pb-1">
    <span class="text-gray-500">系统架构</span>
    <span class="font-medium text-base-content">${host.arch}</span>
  </div>
  <div class="flex justify-between border-b border-base-200 pb-1">
    <span class="text-gray-500">内核信息</span>
    <span class="font-medium text-base-content">${host.kernel}</span>
  </div>
  <div class="flex justify-between border-b border-base-200 pb-1">
    <span class="text-gray-500">运行时间</span>
    <span class="font-medium text-base-content">${host.uptime}</span>
  </div>
</div>
</div>

  <div id="hardwareInfo" class="space-y-2 hidden">
    <div class="grid grid-cols-1 md:grid-cols-1 gap-x-8 gap-y-3 text-sm">
      <div class="flex justify-between border-b border-base-200 pb-1">
        <span class="text-gray-500">CPU型号</span>
        <span class="font-medium text-base-content">${host.cpu_model}</span>
      </div>
      <div class="flex justify-between border-b border-base-200 pb-1">
        <span class="text-gray-500">核心/线程：</span>
        <span class="font-medium text-base-content">${host.cpu_cores}/${host.cpu_threads}</span>
      </div>
      <div class="flex justify-between border-b border-base-200 pb-1">
        <span class="text-gray-500">内存总容量：</span>
        <span class="font-medium text-base-content">${host.memory_total}</span>
      </div>
      <div class="flex justify-between border-b border-base-200 pb-1">
        <span class="text-gray-500">磁盘总容量：</span>
        <span class="font-medium text-base-content">${host.disk_total}</span>
      </div>
      <div class="flex justify-between border-b border-base-200 pb-1">
        <span class="text-gray-500">主板型号：</span>
        <span class="font-medium text-base-content">${host.motherboard}</span>
      </div>
      <div class="flex justify-between border-b border-base-200 pb-1">
        <span class="text-gray-500">BIOS版本：</span>
        <span class="font-medium text-base-content">${host.bios_version}</span>
      </div>
    </div>
  </div>
</div>





          <div class="card glass-card">
            <div class="card-body p-4">
              <div role="tablist" class="tabs tabs-lg tabs-boxed">
                <a role="tab" class="tab tab-active" onclick="switchTab('disk')">磁盘</a>
                <a role="tab" class="tab" onclick="switchTab('cpu')">CPU</a>
                <a role="tab" class="tab" onclick="switchTab('memory')">内存</a>
              </div>
              <div id="chartPanels" class="h-[200px] pt-4">
                <div id="diskPanel" class="h-full flex justify-center items-center">
                  <canvas id="diskChart" class="max-h-[180px]"></canvas>
                </div>
                <div id="cpuPanel" class="hidden h-full flex justify-center items-center">
                  <canvas id="cpuChart" class="max-h-[180px]"></canvas>
                </div>
                <div id="memoryPanel" class="hidden h-full flex justify-center items-center">
                  <canvas id="memoryChart" class="max-h-[180px]"></canvas>
                </div>
              </div>
            </div>
          </div>


<div class="card glass-card ">
  <div class="card-body p-4">
    <h2 class="card-title text-lg mb-4">资源占用Top 5进程</h2>
    <div class="overflow-x-auto">
      <table class="table w-full">
        <thead>
          <tr class="bg-blue-100"><th>进程名</th><th>CPU</th><th>内存</th></tr>
        </thead>
        <tbody>
          ${host.top5.map(p => `<tr><td>${p.name}</td><td>${p.cpu}</td><td>${p.mem}</td></tr>`).join('')}
        </tbody>
      </table>
    </div>
  </div>
</div>
`;
  renderDiskChart(host.disk);
  renderCpuChart(host.cpu);
  renderMemoryChart(host.memory.used, host.memory.total);
  renderLoadChart(host.load);
  switchTab('disk');
}

function renderDiskChart(disks) {
  const diskLabels = disks.map(d => d.mount);
  const usedData = disks.map(d => parseInt(d.used));
  const availData = disks.map(d => parseInt(d.avail));

  // 销毁旧图（如存在）
  if (window.diskChartInstance) {
    window.diskChartInstance.destroy();
  }

  const ctx = document.getElementById('diskChart').getContext('2d');
  window.diskChartInstance = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: diskLabels,
      datasets: [
        {
          label: '已用 (GB)',
          data: usedData,
          backgroundColor: 'rgba(255, 99, 132, 0.7)'
        },
        {
          label: '可用 (GB)',
          data: availData,
          backgroundColor: 'rgba(75, 192, 192, 0.7)'
        }
      ]
    },
    options: {
      responsive: true,
      plugins: {
        legend: { position: 'top' },
        tooltip: { mode: 'index', intersect: false }
      },
      scales: {
        x: {
          stacked: true
        },
        y: {
          stacked: true,
          title: { display: true, text: '空间 (GB)' }
        }
      }
    }
  });

}

function renderCpuChart(cpuUsage) {
  const ctx = document.getElementById('cpuChart').getContext('2d');
  if (cpuChart) cpuChart.destroy();
  cpuChart = new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels: ['已用', '空闲'],
      datasets: [{ data: [cpuUsage, 100 - cpuUsage], backgroundColor: ['#fb923c', '#fef3c7'] }]
    },
    options: { cutout: '70%' }
  });
}

function renderMemoryChart(used, total) {
  const ctx = document.getElementById('memoryChart').getContext('2d');
  if (memoryChart) memoryChart.destroy();
  memoryChart = new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels: ['已用', '剩余'],
      datasets: [{ data: [used, total - used], backgroundColor: ['#34d399', '#d1fae5'] }]
    },
    options: { cutout: '70%' }
  });
}

function renderLoadChart(loadArray) {
  const ctx = document.getElementById('loadChart').getContext('2d');
  window.loadChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['1分钟', '5分钟', '15分钟'],
      datasets: [{
        label: '系统负载',
        data: loadArray,
        backgroundColor: ['#3b82f6', '#facc15', '#ef4444'],
        borderRadius: 4
      }]
    },
    options: {
      responsive: true,
      plugins: {
        legend: { display: false }
      },
      scales: {
        x: { grid: { display: false } },
        y: {
          beginAtZero: true,
          max: 5,
          ticks: { stepSize: 1 }
        }
      }
    }
  });
}


function switchTab(tab) {
  // 1. 切换图表 panel 显示状态
  document.getElementById('diskPanel').classList.add('hidden');
  document.getElementById('cpuPanel').classList.add('hidden');
  document.getElementById('memoryPanel').classList.add('hidden');

  document.getElementById(`${tab}Panel`).classList.remove('hidden');

  // 2. 切换 tab 激活样式
  const tabs = document.querySelectorAll('[role="tab"]');
  tabs.forEach(t => t.classList.remove('tab-active'));

  const activeTab = Array.from(tabs).find(t => t.textContent.trim() === (tab === 'disk' ? '磁盘' : tab === 'cpu' ? 'CPU' : '内存'));
  if (activeTab) {
    activeTab.classList.add('tab-active');
  }
}


  function switchInfoTab(type) {
    const baseTab = document.getElementById('baseTab');
    const hardwareTab = document.getElementById('hardwareTab');
    const baseInfo = document.getElementById('baseInfo');
    const hardwareInfo = document.getElementById('hardwareInfo');

    if (type === 'base') {
      baseTab.classList.add('tab-active');
      hardwareTab.classList.remove('tab-active');
      baseInfo.classList.remove('hidden');
      hardwareInfo.classList.add('hidden');
    } else {
      hardwareTab.classList.add('tab-active');
      baseTab.classList.remove('tab-active');
      hardwareInfo.classList.remove('hidden');
      baseInfo.classList.add('hidden');
    }
  }




//渲染日期组件
flatpickr("#inspectDate", {
  locale: "zh",  // 设置语言为中文
  dateFormat: "Y-m-d",
  defaultDate: new Date(),
  maxDate: "today",
  onChange: function (selectedDates, dateStr) {
    if (dateStr) {
      loadHostsData(dateStr);
    }
  }
});

function loadHostsData(date) {
  fetch(`./data/hosts_${date}.json`)
    .then((res) => {
      if (!res.ok) {
        throw new Error('No data found');
      }
      return res.json();
    })
    .then((data) => {
      if (data && data.length > 0) {
        hosts = data;
        renderHostList();
        showDetails(0);
      } else {
        // 数据为空时的处理
        hostList.innerHTML = '<div class="alert alert-warning">该日期没有巡检数据</div>';
        hostDetails.innerHTML = '';
      }
    })
    .catch((error) => {
      // 网络错误或文件不存在时的处理
      hostList.innerHTML = '<div class="alert alert-warning">该日期没有巡检数据</div>';
      hostDetails.innerHTML = '';
      console.error('加载数据失败:', error);
    });
}

// 页面加载时初始化数据
document.addEventListener('DOMContentLoaded', function () {
  // 获取今天的日期并格式化为 YYYY-MM-DD
  const today = new Date().toISOString().split('T')[0];
  loadHostsData(today);
});


